<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>地图</title>
  <link rel="stylesheet" href="./assets/openLayers/theme/default/style.css">
  <style>
    html,
    body {
      width: 100%;
      height: 100%;
    }

    .map {
      width: 90%;
      height: 90%;
    }
  </style>

</head>

<body>
  <div id="map" class="map"></div>
  <script src="./assets/openLayers/OpenLayers.js"></script>

  <script>
    var resArray = [0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625,
      0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625,
      0.0006866455078125, 0.0003433227539062, 0.0001716613769531, 0.0000858306884766,
      0.0000429153442383, 0.0000214576721191, 0.0000107288360596, 0.0000053644180298];

    //地图初始化方法
    function initMap(div) {
      var map = new OpenLayers.Map({
        div: div,	// 地图显示的容器div(id值)
        displayProjection: "EPSG:4326",  // 控件坐标系, 地图投影坐标系
        controls: [
          new OpenLayers.Control.Navigation(),    // 导航控件
          new OpenLayers.Control.PanZoomBar(),    // 平移缩放控件
          new OpenLayers.Control.MousePosition({  // 鼠标地理坐标控件
            separator: ' , ',
            numDigits: 3
          }),
          new OpenLayers.Control.LayerSwitcher()  // 图层切换控件
        ],
        layers: [], // 地图图层,
        // center: new OpenLayers.LonLat(112.686865, 30.928462), // 地图中心点坐标
        zoom: 10, // 初始缩放级别
      })
      return map;
    }

    // 创建一个WMS图层
    // http://210.12.142.176:7090/onemap22/rest/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetCapabilities&SRS=CGCS2000&ACCOUNT=aHViZWk=&PASSWD=MjAyM2h1YmVpQHNoZW5ndGFp&
    function getWMSLayer(authInfo, isBaseLayer) {
      var wmsLayer = new OpenLayers.Layer.WMS(
        "国产高分卫星影像产品", // 图层前端显示名称
        "http://210.12.142.176:7090/onemap22/rest/wms", // WMS服务器地址
        {
          layers: "WGS84",		// 请求的图层资源
          format: "image/jpeg",		// 请求的瓦片格式
          version: "1.1.1",     // 请求使用的WMS版本
          styles: "",		// 请求的图层样式
          transparent: false		// 是否透明,针对format为png
        },
        {
          projection: "EPSG:4326",    // 图层坐标系
          units: "degrees",
          resolutions: resArray,	// 图层分辨率组
          transitionEffect: "resize",		// 图层前端缩放时的动画效果
          tileSize: new OpenLayers.Size(256, 256),	// 瓦片大小256*256
          tileOrigin: new OpenLayers.LonLat(-180, 90),	// 瓦片切图原点
          isBaseLayer: isBaseLayer,		// 设置为底图且底图唯一
          maxExtent: OpenLayers.Bounds.fromString("70, 5, 140,55"),//wms最大范围
          wrapDateLine: false	//日期变更线，非世界范围不显示
        }
      );
      //重写getUrl加入验证的用户名密码
      if (authInfo.account && authInfo.passwd !== "none") {
        wmsLayer.getURL = function (bounds) {
          bounds = this.adjustBounds(bounds);
          var imageSize = this.getImageSize();
          var newParams = {};
          var reverseAxisOrder = this.reverseAxisOrder();
          newParams.BBOX = this.encodeBBOX ?
            bounds.toBBOX(null, reverseAxisOrder) : bounds.toArray(reverseAxisOrder);
          newParams.WIDTH = imageSize.w;
          newParams.HEIGHT = imageSize.h;
          var requestString = this.getFullRequestString(newParams);
          //构造请求的url
          requestString += "&ACCOUNT=" + authInfo.account + "&PASSWD=" + authInfo.passwd + "&";
          return requestString;
        }
      }
      return wmsLayer;
    }
    //创建一个WMTS图层
    function getWMTSLayer(authInfo, isBaseLayer) {
      var wmtsLayer = new OpenLayers.Layer.WMTS({
        name: "资源三号卫星影像-WMTS",	// 图层前端显示名称
        url: "http://60.194.14.226:7090/rest/wmts",	// WMTS地图服务器地址
        layer: "satImage",	// 图层标识
        version: "1.0.0",     // WMTS版本
        matrixSet: "satImage",	// 瓦片矩阵集标识
        style: "",	// 图层样式
        requestEncoding: "KVP", //图层请求的编码方式
        isBaseLayer: isBaseLayer,   // 设置为底图且底图唯一
        format: "image/jpeg",    // 瓦片请求格式
        transitionEffect: 'resize', // 图层渲染动画效果
        projection: "EPSG:4326",   // 图层坐标系
        units: "degrees",       //单位
        resolutions: resArray,	// 图层分辨率数组
        transparent: false,  // 是否透明,针对format为png
        tileSize: new OpenLayers.Size(256, 256),	// 瓦片大小为256*256
        tileOrigin: new OpenLayers.LonLat(-180, 90),	// 瓦片切片原点
        tileFullExtent: OpenLayers.Bounds.fromString("70, 5, 140,55"),	// WMTS图层最大范围
        wrapDateLine: false		//日期变更线，非世界范围不显示
      });
      if (authInfo.account && authInfo.passwd !== "none") {
        //重写图层对象的getURL方法加入验证的账户密码
        wmtsLayer.getURL = function (bounds) {
          bounds = this.adjustBounds(bounds);
          var url = "";
          if (!this.tileFullExtent || this.tileFullExtent.intersectsBounds(bounds)) {
            var center = bounds.getCenterLonLat();
            var info = this.getTileInfo(center);
            var matrixId = this.matrix.identifier;
            var dimensions = this.dimensions, params;
            if (OpenLayers.Util.isArray(this.url)) {
              url = this.selectUrl([
                this.version, this.style, this.matrixSet,
                this.matrix.identifier, info.row, info.col
              ].join(","), this.url);
            } else {
              url = this.url;
            }
            params = {
              SERVICE: "WMTS",
              REQUEST: "GetTile",
              VERSION: this.version,
              LAYER: this.layer,
              STYLE: this.style,
              TILEMATRIXSET: this.matrixSet,
              TILEMATRIX: this.matrix.identifier,
              TILEROW: info.row,
              TILECOL: info.col,
              FORMAT: this.format
            };
            url = OpenLayers.Layer.Grid.prototype.getFullRequestString.apply(this, [params]);
            //构造请求url
            url += "&ACCOUNT=" + authInfo.account + "&PASSWD=" + authInfo.passwd + "&";
          }
          return url;
        }
      }
      return wmtsLayer;
    }

    var authInfo = {
      account: "hubei",  //填入账户 aHViZWk=
      // passwd: "2023hubei@shengtai",  //填入密码
      // account: "aHViZWk=",  //填入账户
      passwd: "MjAyM2h1YmVpQHNoZW5ndGFp"  //填入密码

    };

    var map = initMap('map'); // 初始化地图
    // var tdtLayer = addTDTLayer();
    var layer = getWMSLayer(authInfo, true); //wms图层
    //var layer = getWMTSLayer(authInfo, true); //wmts图层

    var tdtUrl = "http://t0.tianditu.gov.cn/img_w/wmts?" +
      "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
      "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=6a9f4b408cb773ba60fb639f3b713d61";

    // http://t0.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&layer=img&style=default&tileMatrixSet=w&TileMatrix=${z}&TileRow=${y}&TileCol=${x}&format=tiles&tk=6a9f4b408cb773ba60fb639f3b713d61

    // 创建天地图图层  
    var tianDiTuLayer = new OpenLayers.Layer.XYZ(
      "天地图", // 图层名称  
      [
        "http://t0.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&layer=img&style=default&tileMatrixSet=w&TileMatrix=${z}&TileRow=${y}&TileCol=${x}&format=tiles&tk=6a9f4b408cb773ba60fb639f3b713d61",
      ], // 切片图服务地址  
      {
        isBaseLayer: true, // 是否为基础图层  
        opacity: 1, // 图层透明度 
        isplayInLayerSwitcher: true,
      }
    );

    // 添加天地图图层到地图中  
    // map.addLayer(tianDiTuLayer);
    map.addLayer(layer);
    // map.zoomToExtent(OpenLayers.Bounds.fromString("70, 5, 140,55")); // 移动视图到指定的extent

    //定义marker图层
    var markerLayer = new OpenLayers.Layer.Markers("Markers");

    //随机写的4组坐标
    var LonLatList = [[112.686865, 30.928462], [120, 34], [117, 32], [115, 27]];

    //定义marker图标的尺寸及相对于坐标点的偏移量
    var size = new OpenLayers.Size(40, 40);
    var offset = new OpenLayers.Pixel(-20, -40);

    //生成marker并装载到markerLayer图层中
    LonLatList.forEach(element => {
      var icon = new OpenLayers.Icon('./assets/imgs/plant_sampled.png', size, offset);
      var marker = new OpenLayers.Marker(new OpenLayers.LonLat(element[0], element[1]), icon);

      marker.events.register('touchend', marker, function (evt) {
        // alert(this.icon.url);
        console.log('点击marker');
        // alert('123')
        // OpenLayers.Event.stop(evt);
      });

      markerLayer.addMarker(marker);
    });

    map.addLayer(markerLayer);
    // map.setCenter(new OpenLayers.LonLat(112.686865, 30.928462), 9);


    // 创建矢量图层并将圆形特征添加到图层中  
    var vectorLayer = new OpenLayers.Layer.Vector('Vector Layer');

    // { isBaseLayer: false }
    var vector = new OpenLayers.Layer.Vector('vector');
    map.addLayers([vectorLayer, vector]);

    var style = {
      fillColor: '#000',
      fillOpacity: 0.5,
      strokeWidth: 10
    };

    vector.removeAllFeatures();
    var circle1 = new OpenLayers.Feature.Vector(
      new OpenLayers.Geometry.Point(112, 32),
      {
        type: "circle"
      },
    );
    var circle = new OpenLayers.Feature.Vector(
      OpenLayers.Geometry.Polygon.createRegularPolygon(
        new OpenLayers.Geometry.Point(112, 31),
        100,
        5,
        5
      ),
      {},
      style
    );
    // vector.addFeatures([circle1, circle])
    vector.addFeatures([circle1])

    // 创建圆形  
    var circleFeature = new OpenLayers.Feature.Vector(
      new OpenLayers.Geometry.Polygon([
        new OpenLayers.Geometry.LinearRing([
          new OpenLayers.Geometry.Point(110, 40),
          new OpenLayers.Geometry.Point(110, 30),
          new OpenLayers.Geometry.Point(112, 30),
          new OpenLayers.Geometry.Point(112, 40)
        ])
      ])
    );

    var point = new OpenLayers.Geometry.Point(110, 30);
    // 创建圆的半径长度  
    var radius = 100;

    // var circleFeature = new OpenLayers.Feature.Vector(
    //   new OpenLayers.Geometry.Polygon([
    //     new OpenLayers.Geometry.LinearRing([
    //       point.add([radius, 0]),
    //       point.add([radius, -radius]),
    //       point.add([0, -radius]),
    //       point.add([-radius, -radius]),
    //       point.add([-radius, 0]),
    //       point.add([-radius, radius]),
    //       point.add([0, radius]),
    //       point.add([radius, radius])
    //     ])
    //   ])
    // );


    vectorLayer.addFeatures([circleFeature]);
    // 将矢量图层添加到地图上  
    map.addLayer(vectorLayer);

    var features = new OpenLayers.Feature.Vector(
      new OpenLayers.Geometry.Point(112, 31),
      {
        type: "circle"
      }
    );

    var styles = new OpenLayers.StyleMap({
      "default": {
        graphicName: "${type}",  // 表示要使用的图形类型
        pointRadius: 50,  // 表示点的半径（以像素为单位）
        strokeColor: "#1791fc",  // 表示图形轮廓的颜色
        strokeWidth: 2,
        fillColor: "#1791fc",
        fillOpacity: 0.35
      },
    });

    var layer = new OpenLayers.Layer.Vector("Graphics", {
      styleMap: styles,
      // isBaseLayer: true,
      // renderers: renderer
    });
    layer.addFeatures([features]);
    map.addLayer(layer);


    setTimeout(() => {
      map.setCenter(new OpenLayers.LonLat(112.686865, 30.928462), 4);
      // map.zoomToMaxExtent(markerLayer.getDataExtent());
    }, 1000)

    // if (!map.getCenter()) {
    //   map.zoomToMaxExtent(markerLayer.getDataExtent());
    // }

  </script>

</body>

</html>